from apps.forms import BaseForm
from  wtforms import StringField,IntegerField
from wtforms.validators import  regexp,InputRequired,Length,EqualTo,ValidationError
from utils import zlcache


class SignUpForm(BaseForm):
    telephone = StringField(validators=[regexp(r"1[3456789]\d{9}",message="请输入正确的手机号")])
    sms_captcha = StringField(validators=[regexp(r'\w{4}',message="请输入正确格式的验证码")])
    username = StringField(validators=[Length(2,20)])
    password1 =  StringField(validators=[Length(6,20,message="密码的长度是6~20位")])
    password2 = StringField(validators=[EqualTo("password1",message="两次密码不一致")])
    graph_captcha = StringField(validators=[regexp(r'\w{4}',message="请输入正确格式的验证码")])

    # print(telephone,sms_captcha)

    def validate_sms_captcha(self,field):
        sms_captcha = field.data
        telephone = self.telephone.data
        sms_captcha_mem = zlcache.get(telephone)

        if not sms_captcha or sms_captcha.lower() != sms_captcha_mem.lower():
            raise ValidationError(message="短信验证码不正确")

    def validate_graph_captcha(self,field):
        graph_captcha = field.data

        graph_captcha_mem = zlcache.get(graph_captcha.lower())
        if not graph_captcha_mem:
            raise  ValidationError(message="图形验证码错误")



class SigninForm(BaseForm):
    telephone = StringField(validators=[regexp(r"1[3456789]\d{9}", message="请输入正确的手机号")])
    password = StringField(validators=[Length(6, 20, message="密码的长度是6~20位")])
    remember = IntegerField()


class ADDPostForm(BaseForm):
    title = StringField(validators=[InputRequired(message="请输入帖子名")])
    context = StringField(validators=[InputRequired(message="请输入帖子内容")])
    board_id = IntegerField(validators=[InputRequired(message="请输入板块id")])

class ADDCommentForm(BaseForm):
    post_id = IntegerField(validators=[InputRequired(message="请输入帖子id")])
    context = StringField(validators=[InputRequired(message="请输入评论内容")])
